<i18n locale="zh-CN" lang="yaml">
About: 关于

'You are using {0} browser'          : 您正在使用 {0} 浏览器
'In this system:'                    : '在本系统中：'
'Monospaced font is from {0}'        : '等宽字体来自 {0}'
'Icons used are from {0}'            : '图标来自 {0}'
'Illustrations used are from {0}'    : '插图来自 {0}'
'Code Editor is powered by {0}'      : '代码编辑器基于 {0} 实现'
'Blueprint Canvans is powered by {0}': '蓝图画布基于 {0} 实现'
'Traditional Chinese language resources are generated by {0}': '繁体中文语言资源由 {0} 生成'

'New version {ver} is available, click here to go to the official website': '可以升级到 {ver} 版本，点击此处前往官方网站查看'

Version Information: 版本信息
System Tools       : 系统工具

Version                      : 版本
Architecture                 : 架构
Release Date                 : 发布日期
'Loading...'                 : '加载中...'
Loading System Report        : 正在加载系统报告
Get System Report            : 获取系统报告
Loading Detailed Redis Report: 正在加载 Redis 详细报告
Get Detailed Redis Report    : 获取 Redis 详细报告

Show System Metrics   : 查看系统指标
Show System Logs      : 查看系统日志
Show Abnormal Requests: 查看异常请求

Debug UI Theme : 调试 UI 主题
Debug WebSocket: 调试 WebSocket

Queue Length: 队列长度
Queue Load  : 队列负载
Clear Worker Queues: 清空工作队列
Clear Log and Cache: 清空日志与缓存表

Restart all Servers: 重启所有前端服务（Server）
Restart all Workers and Beat: 重启所有工作单元（Worker、Beat）

Worker Queues cleared: 工作队列已清空
Log and Cache cleared: 日志与缓存表已清空
All Servers will be restarted soon: 所有前端服务（Server）即将重启
All Workers and Beat will be restarted soon: 所有工作单元（Worker、Beat）即将重启

'Full Worker Queue name is DataFluxFunc-worker#workerQueue@{Number}': 完整工作队列名称为 DataFluxFunc-worker#workerQueue@{序号}

<span class="text-bad">Getting detailed Redis report is a heavy operation and may impact the performance of the system.<br>Are you sure you want to continue?</span> : <span class="text-bad">获取 Redis 详细报告是一项重操作，并且可能会影响系统性能。<br>是否确认继续？</span>
Are you sure you want to clear the Worker Queues? : 是否确认清空工作队列？
Are you sure you want to clear the Log and Cache? : 是否确认清空日志与缓存表？
Are you sure you want to restart all the Servers?: 是否确认重启所有前端服务（Server）？
Are you sure you want to restart all the Workers and Beat?: 是否确认重启所有工作单元（Worker、Beat）？
</i18n>

<!-- Generated by OpenCC START -->
<i18n locale="zh-HK" lang="yaml">
? <span class="text-bad">Getting detailed Redis report is a heavy operation and may impact the performance of the system.<br>Are you sure you want to continue?</span>
: <span class="text-bad">獲取 Redis 詳細報告是一項重操作，並且可能會影響系統性能。<br>是否確認繼續？</span>
About: 關於
All Servers will be restarted soon: 所有前端服務（Server）即將重啓
All Workers and Beat will be restarted soon: 所有工作單元（Worker、Beat）即將重啓
Architecture: 架構
Are you sure you want to clear the Log and Cache?: 是否確認清空日誌與緩存表？
Are you sure you want to clear the Worker Queues?: 是否確認清空工作隊列？
Are you sure you want to restart all the Servers?: 是否確認重啓所有前端服務（Server）？
Are you sure you want to restart all the Workers and Beat?: 是否確認重啓所有工作單元（Worker、Beat）？
Blueprint Canvans is powered by {0}: 藍圖畫布基於 {0} 實現
Clear Log and Cache: 清空日誌與緩存表
Clear Worker Queues: 清空工作隊列
Code Editor is powered by {0}: 代碼編輯器基於 {0} 實現
Debug UI Theme: 調試 UI 主題
Debug WebSocket: 調試 WebSocket
Full Worker Queue name is DataFluxFunc-worker#workerQueue@{Number}: 完整工作隊列名稱為 DataFluxFunc-worker#workerQueue@{序號}
Get Detailed Redis Report: 獲取 Redis 詳細報告
Get System Report: 獲取系統報告
Icons used are from {0}: 圖標來自 {0}
Illustrations used are from {0}: 插圖來自 {0}
'In this system:': 在本系統中：
Loading Detailed Redis Report: 正在加載 Redis 詳細報告
Loading System Report: 正在加載系統報告
Loading...: 加載中...
Log and Cache cleared: 日誌與緩存表已清空
Monospaced font is from {0}: 等寬字體來自 {0}
New version {ver} is available, click here to go to the official website: 可以升級到 {ver} 版本，點擊此處前往官方網站查看
Queue Length: 隊列長度
Queue Load: 隊列負載
Release Date: 發佈日期
Restart all Servers: 重啓所有前端服務（Server）
Restart all Workers and Beat: 重啓所有工作單元（Worker、Beat）
Show Abnormal Requests: 查看異常請求
Show System Logs: 查看系統日誌
Show System Metrics: 查看系統指標
System Tools: 系統工具
Traditional Chinese language resources are generated by {0}: 繁體中文語言資源由 {0} 生成
Version: 版本
Version Information: 版本信息
Worker Queues cleared: 工作隊列已清空
You are using {0} browser: 您正在使用 {0} 瀏覽器
</i18n>
<i18n locale="zh-TW" lang="yaml">
? <span class="text-bad">Getting detailed Redis report is a heavy operation and may impact the performance of the system.<br>Are you sure you want to continue?</span>
: <span class="text-bad">獲取 Redis 詳細報告是一項重操作，並且可能會影響系統性能。<br>是否確認繼續？</span>
About: 關於
All Servers will be restarted soon: 所有前端服務（Server）即將重啟
All Workers and Beat will be restarted soon: 所有工作單元（Worker、Beat）即將重啟
Architecture: 架構
Are you sure you want to clear the Log and Cache?: 是否確認清空日誌與快取表？
Are you sure you want to clear the Worker Queues?: 是否確認清空工作佇列？
Are you sure you want to restart all the Servers?: 是否確認重啟所有前端服務（Server）？
Are you sure you want to restart all the Workers and Beat?: 是否確認重啟所有工作單元（Worker、Beat）？
Blueprint Canvans is powered by {0}: 藍圖畫布基於 {0} 實現
Clear Log and Cache: 清空日誌與快取表
Clear Worker Queues: 清空工作佇列
Code Editor is powered by {0}: 程式碼編輯器基於 {0} 實現
Debug UI Theme: 除錯 UI 主題
Debug WebSocket: 除錯 WebSocket
Full Worker Queue name is DataFluxFunc-worker#workerQueue@{Number}: 完整工作佇列名稱為 DataFluxFunc-worker#workerQueue@{序號}
Get Detailed Redis Report: 獲取 Redis 詳細報告
Get System Report: 獲取系統報告
Icons used are from {0}: 圖示來自 {0}
Illustrations used are from {0}: 插圖來自 {0}
'In this system:': 在本系統中：
Loading Detailed Redis Report: 正在載入 Redis 詳細報告
Loading System Report: 正在載入系統報告
Loading...: 載入中...
Log and Cache cleared: 日誌與快取表已清空
Monospaced font is from {0}: 等寬字型來自 {0}
New version {ver} is available, click here to go to the official website: 可以升級到 {ver} 版本，點選此處前往官方網站檢視
Queue Length: 佇列長度
Queue Load: 佇列負載
Release Date: 釋出日期
Restart all Servers: 重啟所有前端服務（Server）
Restart all Workers and Beat: 重啟所有工作單元（Worker、Beat）
Show Abnormal Requests: 檢視異常請求
Show System Logs: 檢視系統日誌
Show System Metrics: 檢視系統指標
System Tools: 系統工具
Traditional Chinese language resources are generated by {0}: 繁體中文語言資源由 {0} 生成
Version: 版本
Version Information: 版本資訊
Worker Queues cleared: 工作佇列已清空
You are using {0} browser: 您正在使用 {0} 瀏覽器
</i18n>
<!-- Generated by OpenCC END -->

<template>
  <transition name="fade">
    <el-container direction="vertical" v-show="$store.state.isLoaded">
      <!-- Header area -->
      <el-header height="60px">
        <h1>{{ $t('About') }}</h1>
      </el-header>

      <!-- Setup area -->
      <el-main>
        <el-row :gutter="20">
          <el-col :span="15">
            <div class="about-form">
              <div class="announce">
                <p>
                  <i18n path="You are using {0} browser">
                    <span class="text-main">{{ T.getBrowser() }} ({{ T.getEngine() }})</span>
                  </i18n>
                </p>
                <p>
                  {{ $t('In this system:') }}
                  <ul>
                    <li>
                      <i18n path="Monospaced font is from {0}">
                        <el-link href="https://typeof.net/Iosevka/" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          Iosevka
                        </el-link>
                      </i18n>
                    </li>
                    <li>
                      <i18n path="Icons used are from {0}">
                        <el-link href="https://fontawesome.com/v4/" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          Font Awesome (v4)
                        </el-link>
                      </i18n>
                    </li>
                    <li>
                      <i18n path="Illustrations used are from {0}">
                        <el-link href="https://flexiple.com/illustrations/" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          Scale by flexiple
                        </el-link>
                      </i18n>
                    </li>
                    <li>
                      <i18n path="Code Editor is powered by {0}">
                        <el-link href="https://codemirror.net/5/" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          Code Mirror (v5)
                        </el-link>
                      </i18n>
                    </li>
                    <li>
                      <i18n path="Blueprint Canvans is powered by {0}">
                        <el-link href="https://site.logic-flow.cn/" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          LogicFlow (v1.2)
                        </el-link>
                      </i18n>
                    </li>
                    <li>
                      <i18n path="Traditional Chinese language resources are generated by {0}">
                        <el-link href="https://github.com/BYVoid/OpenCC" target="_blank">
                          <i class="fa fa-fw fa-external-link"></i>
                          OpenCC (v1.1.6)
                        </el-link>
                      </i18n>
                    </li>
                  </ul>
                </p>
              </div>

              <!-- Server -->
              <el-divider content-position="left"><h1>{{ $t('Version Information') }}</h1></el-divider>

              <el-form label-width="120px">
                <el-form-item :label="$t('Version')">
                  <el-input :readonly="true" :value="FULL_VERSION"></el-input>
                  <el-link type="danger" href="https://func.guance.com/" target="_blank" v-if="common.hasNewVersion()">
                    {{ $t('New version {ver} is available, click here to go to the official website', { ver: $store.state.latestVersion }) }}
                  </el-link>
                </el-form-item>

                <el-form-item :label="$t('Architecture')">
                  <el-input :placeholder="$t('Loading...')" :readonly="true" :value="imageInfo.architecture"></el-input>
                </el-form-item>

                <el-form-item :label="$t('Release Date')">
                  <el-input :placeholder="$t('Loading...')" :readonly="true" :value="releaseDateTEXT"></el-input>
                </el-form-item>
              </el-form>

              <!-- System tools -->
              <el-divider content-position="left"><h1>{{ $t('System Tools') }}</h1></el-divider>

              <el-form label-width="120px">
                <el-form-item>
                  <el-link v-prevent-re-click
                    :disabled="isLoadingSystemReport"
                    @click="getSystemReport">
                    <span v-if="isLoadingSystemReport">
                      <i class="fa fa-fw fa-circle-o-notch fa-spin"></i>
                      {{ $t('Loading System Report') }}
                    </span>
                    <span v-else>{{ $t('Get System Report') }}</span>
                  </el-link>
                  &#12288;
                  <el-link v-prevent-re-click
                    :disabled="isLoadingDetailedRedisReport"
                    @click="getDetailedRedisReport">
                    <span v-if="isLoadingDetailedRedisReport">
                      <i class="fa fa-fw fa-circle-o-notch fa-spin"></i>
                      {{ $t('Loading Detailed Redis Report') }}
                    </span>
                    <span v-else>{{ $t('Get Detailed Redis Report') }}</span>
                  </el-link>

                  <br>
                  <el-link @click="$router.push({ name: 'system-metrics' })">{{ $t('Show System Metrics') }}</el-link>
                  &#12288;
                  <el-link @click="$router.push({ name: 'system-logs' })">{{ $t('Show System Logs') }}</el-link>
                  &#12288;
                  <el-link @click="$router.push({ name: 'abnormal-request-list' })">{{ $t('Show Abnormal Requests') }}</el-link>

                  <br>
                  <el-link @click="$router.push({ name: 'ui-theme-debugger' })">{{ $t('Debug UI Theme') }}</el-link>
                  &#12288;
                  <el-link @click="$router.push({ name: 'guance-websocket-debugger' })">{{ $t('Debug WebSocket') }}</el-link>
                  &#12288;

                  <br>
                  <el-link @click="showClearWorkerQueues = true">{{ $t('Clear Worker Queues') }}</el-link>
                  &#12288;
                  <el-link @click="clearLogCacheTables">{{ $t('Clear Log and Cache') }}</el-link>
                  <br>
                  <el-link @click="restartAllServers">{{ $t('Restart all Servers') }}</el-link>
                  &#12288;
                  <el-link @click="restartAllWorkersAndBeat">{{ $t('Restart all Workers and Beat') }}</el-link>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col :span="9" class="hidden-md-and-down">
          </el-col>
        </el-row>
      </el-main>

      <JSONViewerDialog ref="jsonViewerDialog" :showDownload="true" mode="json" />

      <el-dialog
        :title="$t('Clear Worker Queues')"
        :visible.sync="showClearWorkerQueues"
        width="600px">
        <div class="worker-queue-list">
          <el-table
            :data="showClearWorkerQueuesAll ? workerQueueOverview : nonEmptyWorkerQueueOverview"
            :row-class-name="workerQueueRowClass"
            style="width: 100%">
            <el-table-column :label="$t('Queue')" width="80">
              <template slot-scope="scope">
                <span class="worker-queue-number">#{{ scope.row.queue }}</span>
              </template>
            </el-table-column>

            <el-table-column align="right" :label="$t('Queue Length')">
              <template slot-scope="scope">
                <span>{{ scope.row.workerQueueLength }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="workerQueueLoad" align="right" :label="$t('Queue Load')">
              <template slot-scope="scope">
                <span>{{ scope.row.workerQueueLoad }}</span>
              </template>
            </el-table-column>

            <el-table-column align="right" width="200">
              <template slot="header" slot-scope="scope">
                <el-switch
                  v-model="showClearWorkerQueuesAll"
                  :active-text="$t('Show all')">
                </el-switch>
              </template>
              <template slot-scope="scope">
                <el-link @click="clearWorkerQueues(scope.row.queue)">{{ $t('Clear') }}</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer">
          <el-button type="danger" plain class="float-left" @click="clearWorkerQueues()">{{ $t('Clear All') }}</el-button>
          <el-button @click="showClearWorkerQueues = false">{{ $t('Close') }}</el-button>
        </div>
      </el-dialog>
    </el-container>
  </transition>
</template>

<script>
import Vue from 'vue'
import JSONViewerDialog from '@/components/JSONViewerDialog'

export default {
  name: 'About',
  components: {
    JSONViewerDialog,
  },
  watch: {
    $route: {
      immediate: true,
      async handler(to, from) {
        await this.loadData();
      }
    },
    async showClearWorkerQueues(val) {
      if (!val) return;

      this.updateWorkerQueuesOverview();
    },
  },
  methods: {
    async loadData() {
      this.$store.commit('updateLoadStatus', true);

      // Get image info
      let apiRes = await this.T.callAPI_get('/api/v1/image-info');
      if (apiRes.ok && this.T.notNothing(apiRes.data)) {
        this.imageInfo = {
          architecture    : apiRes.data.ARCHITECTURE,
          releaseTimestamp: apiRes.data.RELEASE_TIMESTAMP,
        };

      } else {
        this.imageInfo = {
          architecture    : this.NO_INFO_TEXT,
          releaseTimestamp: this.NO_INFO_TEXT,
        };
      }
    },
    async getSystemReport() {
      this.isLoadingSystemReport = true;

      // Get system report
      let apiRes = await this.T.callAPI_get('/api/v1/system-report');
      if (apiRes.ok && this.T.notNothing(apiRes.data)) {
        var contentTEXT = JSON.stringify(apiRes.data, null, 2);
        let createTimeStr = this.M().format('YYYYMMDD_HHmmss');
        let fileName = `system-report.${createTimeStr}`;
        this.$refs.jsonViewerDialog.update(contentTEXT, fileName);
      }

      this.isLoadingSystemReport = false;
    },
    async getDetailedRedisReport() {
      if (!await this.T.confirm(this.$t('<span class="text-bad">Getting detailed Redis report is a heavy operation and may impact the performance of the system.<br>Are you sure you want to continue?</span>'))) return;

      this.isLoadingDetailedRedisReport = true;

      // Get detailed Redis report
      let apiRes = await this.T.callAPI_get('/api/v1/detailed-redis-report');
      if (apiRes.ok && this.T.notNothing(apiRes.data)) {
        var contentTEXT = JSON.stringify(apiRes.data, null, 2);
        let createTimeStr = this.M().format('YYYYMMDD_HHmmss');
        let fileName = `detailed-redis-report.${createTimeStr}`;
        this.$refs.jsonViewerDialog.update(contentTEXT, fileName);
      }

      this.isLoadingDetailedRedisReport = false;
    },
    async updateWorkerQueuesOverview() {
      let apiRes = await this.T.callAPI_get('/api/v1/func/overview', {
        query   : { sections: 'queues' },
        feedback: { muteError: true },
      });
      if (!apiRes || !apiRes.ok) return;

      this.workerQueueOverview = apiRes.data.queues;
    },
    async clearWorkerQueues(queues) {
      if (!await this.T.confirm(this.$t('Are you sure you want to clear the Worker Queues?'))) return;

      queues = this.T.asArray(queues);
      let apiRes = await this.T.callAPI('post', '/api/v1/debug/worker-queues/do/clear', {
        body :    { workerQueues: queues },
        feedback: { okMessage: `${this.$t('Worker Queues cleared')}` },
      });

      if (!apiRes || !apiRes.ok) return;

      this.updateWorkerQueuesOverview();
    },
    async clearLogCacheTables() {
      if (!await this.T.confirm(this.$t('Are you sure you want to clear the Log and Cache?'))) return;

      let apiRes = await this.T.callAPI('post', '/api/v1/debug/log-cache-tables/do/clear', {
        feedback: { okMessage: `${this.$t('Log and Cache cleared')}` },
      });
    },
    async restartAllServers() {
      if (!await this.T.confirm(this.$t('Are you sure you want to restart all the Servers?'))) return;

      let apiRes = await this.T.callAPI('post', '/api/v1/temporary-flags/:id/do/set', {
        params  : { id: 'restartAllServers' },
        body    : {  },
        feedback: { okMessage: `${this.$t('All Servers will be restarted soon')}` },
      });
    },
    async restartAllWorkersAndBeat() {
      if (!await this.T.confirm(this.$t('Are you sure you want to restart all the Workers and Beat?'))) return;

      let apiRes = await this.T.callAPI('post', '/api/v1/temporary-flags/:id/do/set', {
        params  : { id: 'restartAllWorkersAndBeat' },
        body    : {  },
        feedback: { okMessage: `${this.$t('All Workers and Beat will be restarted soon')}` },
      });
    },
    workerQueueRowClass(scope) {
      if (scope.row.workerQueueLength <= 0) return 'text-info';

      if (scope.row.workerQueueLoad < 50) {
        return 'text-main';
      } else if (scope.row.workerQueueLoad < 99) {
        return 'text-watch';
      } else {
        return 'text-bad';
      }
    },
  },
  computed: {
    NO_INFO_TEXT() {
      return this.$t('No Data');
    },
    FULL_VERSION() {
      if (this.$store.getters.SYSTEM_INFO('EDITION')) {
        return `${this.$store.getters.SYSTEM_INFO('VERSION')} (${this.$store.getters.SYSTEM_INFO('EDITION')})`;
      } else {
        return this.$store.getters.SYSTEM_INFO('VERSION');
      }
    },
    releaseDateTEXT() {
      let releaseTimestamp = this.imageInfo.releaseTimestamp * 1000 ||  Date.now();
      let releaseDate      = this.M.utc(releaseTimestamp).locale(this.$store.getters.uiLocale).format('YYYY-MM-DD HH:mm:ss Z');
      let releaseToNow     = this.T.toNow(releaseTimestamp);

      return `${releaseDate} ${this.$t('(')}${releaseToNow}${this.$t(')')}`
    },
    nonEmptyWorkerQueueOverview() {
      return this.workerQueueOverview.filter(q => q.workerQueueLength > 0);
    },
  },
  props: {
  },
  data() {
    return {
      imageInfo: {},

      isLoadingSystemReport       : false,
      isLoadingDetailedRedisReport: false,

      showClearWorkerQueues: false,
      showClearWorkerQueuesAll: false,
      workerQueueOverview  : [],
      workerQueuesToClear  : [],
    }
  },
}
</script>

<style scoped>
.announce {
  position: relative;
  left: 45px;
  top: -20px;
}
.announce li {
  margin-top: 10px;
}
.about-form {
  width: 600px;
}

.worker-queue-list {
  min-height: 200px;
}
.worker-queue-number {
  font-size: 20px;
}
</style>
<style>
.el-table th .el-switch {
  display: inline-flex;
  line-height: 20px;
}
</style>
